// 云对象教程: https://uniapp.dcloud.net.cn/uniCloud/cloud-obj
// 记账本云对象 - 处理记账记录的增删改查
const uniID = require('uni-id-common')
const db = uniCloud.database()
const dbCmd = db.command

module.exports = {
	_before: async function () {
		// 通用预处理器 - 登录校验
		this.uniID = uniID.createInstance({ context: this })
		const auth = await this.uniID.checkToken(this.getUniIdToken())
		console.log('-=====', auth)
		if (auth.errCode) {
			return {
				errCode: auth.errCode,
				errMsg: auth.errMsg
			}
		} else {
			this.uid = auth.uid
		}
	},
	
	/**
	 * 添加记账记录
	 * @param {object} data 记账数据 {type, amount, category_id, note, date}
	 * @returns {object} 返回结果
	 */
	async addRecord(data) {
		if (!data.amount || !data.type || !data.date) {
			return { code: 1, msg: '缺少必要字段' }
		}
		
		const record = {
			user_id: this.uid,
			category_id: data.category_id || null,
			type: data.type, // 支出 or 收入
			amount: Number(data.amount),
			note: data.note || '',
			date: data.date,
			create_time: Date.now()
		}
		
		const res = await db.collection('records').add(record)
		return { code: 0, msg: '记账成功', id: res.id }
	},
	
	/**
	 * 获取当前用户的记账记录列表
	 * @param {number} limit 每页数量
	 * @param {number} skip 跳过数量
	 * @param {string} type 类型筛选（支出/收入）
	 * @param {string} startDate 开始日期
	 * @param {string} endDate 结束日期
	 * @returns {object} 返回记录列表
	 */
	async listRecords({ limit = 20, skip = 0, type, startDate, endDate } = {}) {
		const $ = db.command.aggregate
		
		// 构建查询条件
		let matchCondition = { user_id: this.uid }
		if (type) {
			matchCondition.type = type
		}
		if (startDate && endDate) {
			matchCondition.date = dbCmd.gte(startDate).and(dbCmd.lte(endDate))
		}
		
		const res = await db.collection('records')
			.aggregate()
			.match(matchCondition)
			.lookup({
				from: 'categories',
				localField: 'category_id',
				foreignField: '_id',
				as: 'category'
			})
			.project({
				amount: 1,
				note: 1,
				type: 1,
				date: 1,
				category_name: $.arrayElemAt(['$category.name', 0]),
				category_icon: $.arrayElemAt(['$category.icon', 0]),
				create_time: 1
			})
			.sort({ date: -1, create_time: -1 })
			.skip(skip)
			.limit(limit)
			.end()
		
		return { code: 0, data: res.data }
	},
	
	/**
	 * 获取记录详情
	 * @param {string} id 记录ID
	 * @returns {object} 记录详情
	 */
	async getRecord(id) {
		const res = await db.collection('records')
			.doc(id)
			.get()
		
		if (res.data.length === 0 || res.data[0].user_id !== this.uid) {
			return { code: 1, msg: '记录不存在' }
		}
		
		return { code: 0, data: res.data[0] }
	},
	
	/**
	 * 更新记账记录
	 * @param {string} id 记录ID
	 * @param {object} data 更新的数据
	 * @returns {object} 返回结果
	 */
	async updateRecord(id, data) {
		// 先检查权限
		const checkRes = await db.collection('records')
			.doc(id)
			.get()
		
		if (checkRes.data.length === 0 || checkRes.data[0].user_id !== this.uid) {
			return { code: 1, msg: '无权限操作' }
		}
		
		// 只允许更新这些字段
		const updateData = {}
		if (data.amount !== undefined) updateData.amount = Number(data.amount)
		if (data.type !== undefined) updateData.type = data.type
		if (data.category_id !== undefined) updateData.category_id = data.category_id
		if (data.note !== undefined) updateData.note = data.note
		if (data.date !== undefined) updateData.date = data.date
		
		await db.collection('records')
			.doc(id)
			.update(updateData)
		
		return { code: 0, msg: '更新成功' }
	},
	
	/**
	 * 删除一条记录
	 * @param {string} id 记录ID
	 * @returns {object} 返回结果
	 */
	async deleteRecord(id) {
		await db.collection('records')
			.where({ _id: id, user_id: this.uid })
			.remove()
		return { code: 0, msg: '删除成功' }
	},
	
	/**
	 * 获取统计数据
	 * @param {string} startDate 开始日期
	 * @param {string} endDate 结束日期
	 * @returns {object} 统计数据
	 */
	async getStatistics({ startDate, endDate } = {}) {
		const $ = db.command.aggregate
		
		// 构建查询条件
		let matchCondition = { user_id: this.uid }
		if (startDate && endDate) {
			matchCondition.date = dbCmd.gte(startDate).and(dbCmd.lte(endDate))
		}
		
		// 按类型统计总额
		const totalRes = await db.collection('records')
			.aggregate()
			.match(matchCondition)
			.group({
				_id: '$type',
				total: $.sum('$amount'),
				count: $.sum(1)
			})
			.end()
		
		// 按分类统计
		const categoryRes = await db.collection('records')
			.aggregate()
			.match(matchCondition)
			.lookup({
				from: 'categories',
				localField: 'category_id',
				foreignField: '_id',
				as: 'category'
			})
			.group({
				_id: {
					type: '$type',
					category_id: '$category_id',
					category_name: $.arrayElemAt(['$category.name', 0]),
					category_icon: $.arrayElemAt(['$category.icon', 0])
				},
				total: $.sum('$amount'),
				count: $.sum(1)
			})
			.sort({ total: -1 })
			.end()
		
		// 整理数据
		let income = 0, expense = 0
		totalRes.data.forEach(item => {
			if (item._id === '收入') income = item.total
			if (item._id === '支出') expense = item.total
		})
		
		return {
			code: 0,
			data: {
				income,
				expense,
				balance: income - expense,
				categoryStats: categoryRes.data
			}
		}
	}
}
